package com.gis.controller;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.units.qual.A;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gis.dto.SLDStyleDto;
import com.gis.entity.ColorMapEntry;
import com.gis.entity.GeoServerStyle;
import com.gis.entity.LayerData;
import com.gis.entity.SLDStyle;
import com.gis.result.ResponseResult;
import com.gis.service.GeoServerRestApi;
import com.gis.service.LayerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;


@RestController
@RequestMapping("/style")
@Tag(name = "样式管理", description = "样式相关接口")
@Slf4j
public class StyleController {
    @Autowired
    private GeoServerRestApi geoServerRestApi;

    @Autowired
    private LayerService layerService;

    @Value("${gis.geoserver.default_style}")
    private String defaultStyle;

    @Operation(summary = "创建图层样式", description = "创建图层样式")
    @PostMapping("createStyle")
    public ResponseResult<?> createStyle(@RequestBody SLDStyleDto styleDto) {
        SLDStyle sldStyle = new SLDStyle();
        BeanUtils.copyProperties(styleDto, sldStyle);
        // 1. post请求创建样式
        GeoServerStyle geoServerStyle = new GeoServerStyle(sldStyle.getName());
        this.geoServerRestApi.createStyle(Map.of("style", geoServerStyle));
        // 2. 根据List<ColorMapEntry>自动生成样式
        this.geoServerRestApi.modifyStyle(sldStyle.getName(), sldStyle.getSLDStyle());
        return ResponseResult.success("样式创建成功");
        
    }

    @Operation(summary = "删除图层样式", description = "删除图层样式")
    @DeleteMapping("deleteStyle/{styleName}")
    public ResponseResult<?> deleteStyle(@PathVariable String styleName) throws Exception {
        // 1. 删除样式
        this.geoServerRestApi.deleteStyle(styleName);
        // 2. 指定的图层样式解绑
        QueryWrapper<LayerData> queryWrapper = new QueryWrapper<>();
        Map<String, Object> map = Map.of("style", styleName);
        queryWrapper.allEq(map, false);
        List<LayerData> layers = this.layerService.list(queryWrapper);
        for (LayerData layer : layers) {
            this.layerService.modifyLayer(layer.getOriginName(), defaultStyle);
        }
        return ResponseResult.success("样式删除成功");
    }

    @Operation(summary = "查看样式图层", description = "查看样式图层")
    @GetMapping("/detailStyle/{styleName}")
    public ResponseResult<?> detailStyle(@PathVariable String styleName) {
        String xmlRes = this.geoServerRestApi.detailStyle(styleName);
        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            Document document = saxBuilder.build(new StringReader(xmlRes));
            Element rootElement = document.getRootElement();
            List<ColorMapEntry> colorMapEntries = new ArrayList<>();
            Namespace sldNs = Namespace.getNamespace("sld", "http://www.opengis.net/sld");
            @SuppressWarnings("unchecked")
            List<Element> entries = rootElement
            .getChild("NamedLayer", sldNs)
            .getChild("UserStyle", sldNs)
            .getChild("FeatureTypeStyle", sldNs)
            .getChild("Rule", sldNs)
            .getChild("RasterSymbolizer", sldNs)
            .getChild("ColorMap", sldNs)
            .getChildren("ColorMapEntry", sldNs);

            // 打印信息
            for (Element entry : entries) {
                ColorMapEntry colorMapEntry = new ColorMapEntry();
                colorMapEntry.setColor(entry.getAttributeValue("color"));
                colorMapEntry.setOpacity(entry.getAttributeValue("opacity"));
                colorMapEntry.setQuantity(entry.getAttributeValue("quantity"));
                colorMapEntry.setLabel(entry.getAttributeValue("label"));
                colorMapEntries.add(colorMapEntry);
            }
            return ResponseResult.success(colorMapEntries);
        } catch (Exception e) {
            log.error("Error parsing style XML", e);
            return ResponseResult.fail("样式详情获取失败");
        }
    }

    @Operation(summary = "查看所有样式列表", description = "查看所有样式列表")
    @GetMapping("/listStyles")
    public ResponseResult<?> listStyles() {
        Map<String, Object> styles = this.geoServerRestApi.listStyles();
        return ResponseResult.success(styles);
    }
    // TODO: 添加图层时的验证逻辑
}
